package com.cqjtu.eecs.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cqjtu.eecs.entity.AnalysisType;
import com.cqjtu.eecs.entity.params.analysisType.AnalysisTypeAddParams;
import com.cqjtu.eecs.entity.params.analysisType.AnalysisTypeUpdateParams;
import com.cqjtu.eecs.service.IAnalysisTypeService;
import com.cqjtu.eecs.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  徐文升
 * @since 2022-02-28
 */
@RestController
@RequestMapping("/analysis-type")
@Api(tags = "分析类别接口")
public class AnalysisTypeController {

    @Autowired
    private IAnalysisTypeService analysisTypeService;

    @PostMapping()
    @ApiOperation(value = "新增分析类别")
    public Result addAnalysisType(@RequestBody @Valid AnalysisTypeAddParams analysisTypeAddParams) {
        //analysisTypeAddParams转analysisType
        AnalysisType analysisType = new AnalysisType();
        BeanUtils.copyProperties(analysisTypeAddParams, analysisType);

        //插入分析类别
        boolean save = false;
        try {
            save = analysisTypeService.save(analysisType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (save)
            return Result.success();
        return Result.error();
    }

    @GetMapping("/top-analysis-type")
    @ApiOperation(value = "查询所有顶级分析类别")
    public List<AnalysisType> getAllTopAnalysisType() {
        return analysisTypeService.list(new QueryWrapper<AnalysisType>().isNull("pre_analysis_type_id"));
    }

    @GetMapping("/sub-analysis-type/{analysisTypeId}")
    @ApiOperation(value = "获取某分析类别的所有下级分析类别")
    public List<AnalysisType> getAllSubAnalysisTypeById(@PathVariable int analysisTypeId) {
        return analysisTypeService.list(new QueryWrapper<AnalysisType>().eq("pre_analysis_type_id", analysisTypeId));
    }

    @PutMapping()
    @ApiOperation(value = "修改分析类别")
    public Result updateAnalysisType(@RequestBody @Valid AnalysisTypeUpdateParams analysisTypeUpdateParams) {
        //analysisTypeUpdateParams转analysisType
        AnalysisType analysisType = new AnalysisType();
        BeanUtils.copyProperties(analysisTypeUpdateParams, analysisType);

        //修改分析类别
        boolean update = false;
        try {
            update = analysisTypeService.update(analysisType, new UpdateWrapper<AnalysisType>().eq("analysis_type_id", analysisType.getAnalysisTypeId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (update)
            return Result.success();
        return Result.error();
    }

}
